<template>
  <div class="loanBusiness">
    <Tabs :option="tabsOption" @change="tabsChange"></Tabs>
    <div v-for="(item,index) in tabsOption.column" :key="index">
      <div v-if="changeTabOption.prop === item.prop">
        <div v-for="(item2, index2) in item.type" :key="item.prop + index2">
          <SimpleData :simpleData="simpleData" :option="simpleOption" :buttonSelf="simpleButtonArray"
                      @selfButton="simpleButton" v-if="item2 === 'simpleData'"></SimpleData>
          <avue-crud
            v-if="item2 === 'table'"
            :option="tableOption"
            :data="tableData"
            :page="tablePage"
            :key="index2"
            @search-change="search"
            @search-reset="searchClear"
            @size-change="sizeChangeSearch"
            @current-change="currentChangeSearch">
            <template slot-scope="scope" slot="menu" style="float: right">
              <el-button size="small" type="text" v-for="(item,index) in tableButtonArray" :key="'cc' + index"
                         @click="tableButton(item.prop, scope.row)">{{item.label}}
              </el-button>
            </template>
          </avue-crud>
        </div>
      </div>
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      top="5%"
      width="90%">
      <el-scrollbar style="height: 450px;">
        <SimpleData v-if="dialogTableFlag === 'simpleData'" :simpleData="dialogSimpleData" :option="dialogSimpleOption" :buttonSelf="dialogSimpleButtonArray"
                    @selfButton="simpleButton"></SimpleData>
        <avue-crud
          style="margin: 10px 0px;"
          v-if="dialogTableFlag === 'table'"
          :key='mathRandom'
          :option="dialogTableOptions"
          :data="dialogTableData"
          :page="dialogTablePage"
          @search-change="dialogSearch"
          @search-reset="dialogSearchClear"
          @size-change="dialogSizeChange"
          @current-change="dialogCurrentChange">
          <template slot="expand" slot-scope="{row}">
            短信内容：{{row.content}}
          </template>
        </avue-crud>
        <div v-if="dialogTableFlag === 'form'">
          <avue-form v-model="selectVal" :option="dialogFormOption" ref="form" />
          <el-radio-group v-model="content">
            <el-radio
              v-for="(item3, index3) in msgTemplate"
              :label="item3.content"
              :key="index3"
              class="el-formMsg-radio"
              style="margin: 10px 0px;"
            >{{item3.content}}</el-radio>
          </el-radio-group>
        </div>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="dialogTableFlag === 'form'" type="primary" @click="dialogSendMessage">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Axios from 'axios'
  import Tabs from '@/components/common/Tabs'
  import SimpleData from '@/components/common/SimpleData'
  import {queryLoss, sendContentMessage} from '@/api/bankBiz/loss/loss'
  import {messageTemplate, saveShortMessage, getShortMessage} from '@/api/bankBiz/personal/personInfo'

  export default {
    name: 'short-message',
    components: {
      Tabs,
      SimpleData
    },
    data() {
      return {
        namespace: 'Personal',
        nameFlag: 'sendShortMessage',
        type: [],
        returnType: [],
        tabsOption: {},
        changeTabOption: {},
        tableOption: {},
        tableButtonArray: [],
        tablePage: {},
        query: {
          'namespace': '',
          'key': ''
        },
        tableTotalData: [],
        tableData: [],
        // 表单相关
        simpleData: {},
        simpleOption: {},
        simpleButtonArray: [],
        // 详情相关
        dialogVisible: false,
        dialogTitle: '',
        dialogOption: {},
        dialogTableFlag: '',
        dialogSimpleData: {},
        dialogSimpleOption: {},
        dialogSimpleButtonArray: [],
        dialogTableData: [],
        dialogTableOptions: {},
        dialogTablePage: {
          'pageSizes': [20, 30, 50, 100],
          'currentPage': 1,
          'total': 0,
          'pageSize': 20
        },
        mathRandom: '',
        shortHistoryParams: {
          'currentPage': 1,
          'pageSize': 20
        },
        dialogFormOption: {},
        selectVal: {},
        msgTemplate: [],
        content: ''
      }
    },
    created() {
      this.initOptions()
    },
    mounted() {

    },
    methods: {
      // 初始化配置
      initOptions() {
        this.type = this.$route.meta.type
        // 循环组件，初始化赋值
        for (let i = 0; i < this.type.length; i++) {
          // 1 页签初始化
          if ('tabs' === this.type[i]) {
            let tabsViewOption = personalOptions.tabsViewOption
            this.tabsOption = tabsViewOption[this.nameFlag].tabsOption
            // 默认第一个页签
            this.changeTabOption.prop = this.tabsOption.column[0].prop
            this.returnType = this.tabsOption.column[0].type
            // 详情相关
            this.dialogOption = this.tabsOption.column[0].detailOptions
            this.dialogSimpleButtonArray = this.tabsOption.column[0].detailOptions.simpleButtonArray

            // 初始化第一个页签配置
            for (let j = 0; j < this.tabsOption.column[0].type.length; j++) {
              if ('table' == this.tabsOption.column[0].type[j]) {
                this.tableOption = this.tabsOption.column[0].tableOptions
                this.tablePage = this.tabsOption.column[0].tablePage
                this.tableButtonArray = this.tabsOption.column[0].tableButtonArray
              } else if ('simpleData' == this.tabsOption.column[0].type[j]) {
                this.simpleOption = this.tabsOption.column[0].simpleOptions
                this.simpleButtonArray = this.tabsOption.column[0].simpleButtonArray
              }
            }
            if (this.tabsOption.column[0].query) {
              this.query.query = Object.assign({}, this.tabsOption.column[0].query)
            }
            this.query.namespace = this.namespace
            this.query.key = this.tabsOption.column[0].prop
          }
        }
        this.commonQueryData()
      },
      // 切换页签
      tabsChange(column) {
        console.log(column)
        let data = []
        for (let i = 0; i < this.tabsOption.column.length; i++) {
          if (this.tabsOption.column[i].prop === column.prop) {
            data = this.tabsOption.column[i]
          }
        }
        this.changeTabOption = data
        this.returnType = data.type
        if (data.query) {
          this.query.query = Object.assign({}, data.query)
        }
        this.query.key = data.prop
        // 详情相关
        this.dialogOption = data.detailOptions
        this.dialogSimpleButtonArray = data.detailOptions.simpleButtonArray
        for (let i = 0; i < data.type.length; i++) {
          if ('table' == data.type[i]) {
            this.tableOption = data.tableOptions
            this.tablePage = data.tablePage
            this.tableButtonArray = data.tableButtonArray
            this.tableData = []
            this.tableTotalData = []
          } else if ('simpleData' == data.type[i]) {
            this.simpleOption = data.simpleOptions
            this.simpleButtonArray = data.simpleButtonArray
          }
        }
        this.commonQueryData()
      },
      // 搜索按钮事件
      search(params, done) {
        Object.keys(params).forEach(keys => {
          if (params[keys]) {
            this.query.query[keys] = params[keys]
          }
        })
        this.commonQueryData(true)
        if (done) {
          done()
        }
      },
      searchClear() {
        this.query.query.accountNo = ''
      },
      // 调用接口获取数据
      commonQueryData(flag) {
        // 初始化接口入参
        if (this.query.query.customerNo) {
          this.query.query.customerNo = sessionStorage.getItem('customerNo')
        }
        if (this.query.query.accountNo && !flag) {
          this.query.query.accountNo = ''
        }
        // 初始化分页参数
        this.query.query.currentPage = 1
        this.query.query.pageSize = 20
        this.tablePage.currentPage = 1
        this.tablePage.pageSize = 20
        this.tablePage.total = 0
        // 短消息发送
        if ('sendShortMessageData' == this.query.key) {
          this.simpleData = {
            'customerName': sessionStorage.getItem('accName'),
            'idType': sessionStorage.getItem('customerIdType'),
            'idNo': sessionStorage.getItem('customerIdNo'),
            'accountNo': sessionStorage.getItem('bankNo'),
            'phone': sessionStorage.getItem('customerPhone')
          }
          return
        }
        // 调用公共业务接口
        queryLoss(this.query).then((res) => {
          console.log('response data is: ' + JSON.stringify(res.data))
          if (200 == res.data.code) {
            for (let i = 0; i < this.returnType.length; i++) {
              if ('table' == this.returnType[i]) {
                if (res.data.data.resList == null || res.data.data.resList == undefined) {
                  this.tableData = []
                  this.tableTotalData = []
                  this.tablePage.total = 0
                  return
                }
                this.tableData = res.data.data.resList
                this.tableTotalData = res.data.data.resList
                // 理财产品超市、当前持有、当前委托、基金产品超市
                if ('wealthProductSupermarket' ==  this.query.key) {
                  console.log(parseInt(res.data.data.totalNum))
                  this.tablePage.total = parseInt(res.data.data.totalNum)
                  return
                }
                // 兼容客户端分页
                if ('Client' == window.Settings.pageType) {
                  this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
                  this.tablePage.total = this.tableTotalData.length
                }
              } else if ('simpleData' == this.returnType[i]) {
                this.simpleData = res.data.data
              }
            }
          } else {
            let errMsg = res.data.message
            window.globalUiKit.notify('提示', errMsg, 'error')
            this.tableData = []
            this.tableTotalData = []
            this.tablePage.total = 0
          }
        }).catch((err) => {
          this.tableData = []
          this.tableTotalData = []
          this.tablePage.total = 0
          console.log(err)
        })
      },
      // 切换行数
      sizeChangeSearch(val) {
        this.query.query.currentPage = 1
        this.query.query.pageSize = val
        // 理财产品超市、当前持有、当前委托、基金产品超市
        if ('wealthProductSupermarket' == this.query.key) {
          queryLoss(this.query).then((res) => {
            if(res.data.code == 200){
              this.tablePage.total = parseInt(res.data.data.totalNum)
              this.tableData = res.data.data.resList
            }else{
              this.tablePage.total = 0
              this.tableData = []
              window.globalUiKit.notify('提示', res.data.message, 'error')
            }
          }).catch((err) => {
            console.log(err)
          })
          return
        }
        // 兼容客户端分页
        if ('Client' == window.Settings.pageType) {
          this.tablePage.currentPage = 1
          this.tablePage.pageSize = val
          this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
          this.tablePage.total = this.tableTotalData.length
          return
        }
      },
      // 切换页码
      currentChangeSearch(val) {
        this.query.query.currentPage = val
        console.log('切换页码')
        // 理财产品超市、当前持有、当前委托、基金产品超市
        if ('wealthProductSupermarket' ==  this.query.key) {
          queryLoss(this.query).then((res) => {
            if(res.data.code == 200){
              this.tablePage.total = parseInt(res.data.data.totalNum)
              this.tableData = res.data.data.resList
            }else{
              this.tablePage.total = 0
              this.tableData = []
              window.globalUiKit.notify('提示', res.data.message, 'error')
            }
          }).catch((err) => {
            console.log(err)
          })
          return
        }
        // 兼容客户端分页
        if ('Client' == window.Settings.pageType) {
          this.tablePage.currentPage = val
          this.tableData = this.tableTotalData.slice((this.tablePage.currentPage - 1) * this.tablePage.pageSize, this.tablePage.currentPage * this.tablePage.pageSize)
          this.tablePage.total = this.tableTotalData.length
          return
        }
      },
      // 表格按钮操作
      tableButton(prop, row) {
        console.log('table prop is: ' + prop + ', table row is: ' + JSON.stringify(row))
      },
      // simpleData自定义事件
      simpleButton(prop) {
        console.log('prop is: ' + prop)
        this.dialogVisible = true
        this.dialogSimpleOption = {}
        this.dialogTableOptions = {}
        this.mathRandom = Math.random()*10
        // 短信发送
        if ('personal-shortMessage-send' === prop) {
          this.dialogTableFlag = 'form'
          this.content = ''
          this.dialogTitle = this.dialogOption.saveShortMessage.title
          this.dialogFormOption = this.dialogOption.saveShortMessage.formOptions
        }
        // 历史短信查询
        else if ('personal-shortMessage-searchHistory' === prop) {
          this.dialogTableFlag = 'table'
          this.dialogTitle = this.dialogOption.shortMessageList.title
          this.dialogTableOptions = this.dialogOption.shortMessageList.tableOptions
          this.shortHistoryParams = {
            'phone': sessionStorage.getItem('customerPhone'),
            'transferDate': [new Date(new Date().setDate(new Date().getDate() - 5)).Format('yyyyMMdd'), new Date().Format('yyyyMMdd')],
            'currentPage': 1,
            'pageSize': 20
          }
          this.getShortMessageList()
        }
      },
      dialogSearch(params, done) {
        console.log('short message params: ' + JSON.stringify(params))
        Object.keys(params).forEach(keys => {
          if (params[keys]) {
            this.shortHistoryParams[keys] = params[keys]
          }
        })
        if (params.transferDate) {
          if (Utils.dateRange(params.transferDate[0], params.transferDate[1]) > 365) {
            window.globalUiKit.notify('提示', '交易日期范围不能超过一年！', 'error')
            done()
            return
          }
        }
        this.getShortMessageList()
        if (done) {
          done()
        }
      },
      dialogSearchClear() {
        this.shortHistoryParams = {
          'phone': sessionStorage.getItem('customerPhone'),
          'transferDate': [new Date(new Date().setDate(new Date().getDate() - 5)).Format('yyyyMMdd'), new Date().Format('yyyyMMdd')],
          'currentPage': 1,
          'pageSize': 20
        }
      },
      // 根据业务类型获取短信模板
      getMessageTemplate(value) {
        let params = {
          'columns':[{
              'cond': 0,
              'name': 'classify',
              'value': value
          }],
          'limit': 10000,
          'offset': 0
        }
        messageTemplate(params).then((res) => {
          if (200 == res.data.code) {
            this.msgTemplate = res.data.data.listData
          } else {
            this.msgTemplate = []
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 确认关闭弹框
      dialogSendMessage() {
        if (!this.content) {
          window.globalUiKit.notify('提示', '请先选择短信模板！', 'error')
          return
        }
        if (this.content.indexOf('userid=') > -1) {
          this.content = this.content.replace('userid=', 'userid=' + Constants.Agent.userId)
        }
        this.$confirm(this.content, '短信发送', {
          confirmButtonText: '发送',
          cancelButtonText: '取消',
          type: ''
        }).then(() => {
          let params = {
            'content': this.content,
            'phone': sessionStorage.getItem('customerPhone'),
            'agentName': Constants.Agent.agentName,
            'agentId': Constants.Agent.agentId,
            'smsType': '综合业务'
          }
          sendContentMessage(params).then(res => {
            if (200 == res.data.code) {
              window.globalUiKit.notify('提示', '短信发送成功！', 'success')
              this.saveShortMessageList('已发送')
              this.dialogVisible = false
            } else {
              window.globalUiKit.alert('短信发送失败', '失败原因：' + res.data.message + '；入参：' + JSON.stringify(params))
              this.saveShortMessageList('发送失败')
            }
          }).catch(error => {
            console.log(error)
            window.globalUiKit.alert('短信发送失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
            this.saveShortMessageList('发送失败')
          })
        }).catch(() => {
          console.log('取消发送！')
        });
      },
      // 保存短信记录接口
      saveShortMessageList(status) {
        let params = {
          'status': status,
          'businessType': this.selectVal.businessType,
          'content': this.content,
          'phone': sessionStorage.getItem('customerPhone'),
          'customerName': sessionStorage.getItem('accName'),
          'idType': sessionStorage.getItem('customerIdType'),
          'idNo': sessionStorage.getItem('customerIdNo'),
          'cardNo': sessionStorage.getItem('bankNo'),
          'sessionId': Constants.Model.sid,
          'agentName': Constants.Agent.agentName,
          'agentId': Constants.Agent.agentId
        }
        saveShortMessage(params).then((res) => {
          if (200 == res.data.code) {
            console.log('保存短信记录成功')
          } else {
            window.globalUiKit.alert('短信记录保存失败', '失败原因：' + res.data.message + '；入参：' + JSON.stringify(params))
          }
        }).catch(error => {
          window.globalUiKit.alert('短信记录保存失败', '失败原因：' + error + '；入参：' + JSON.stringify(params))
        })
      },
      // 获取短信历史记录接口
      getShortMessageList() {
        this.shortHistoryParams.pageSize = 20
        this.shortHistoryParams.currentPage = 1
        this.dialogTablePage.pageSize = 20
        this.dialogTablePage.currentPage = 1
        this.dialogTablePage.total = 0
        this.getShortMessageFun()
      },
      // 接口封装
      getShortMessageFun() {
        getShortMessage(this.shortHistoryParams).then((res) => {
          if (200 == res.data.code) {
            this.dialogTableData = res.data.data.resList
            this.dialogTablePage.total = res.data.data.total
          } else {
            this.dialogTableData = []
            this.dialogTablePage.total = 0
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 切换行数
      dialogSizeChange(val) {
        this.shortHistoryParams.pageSize = val
        this.shortHistoryParams.currentPage = 1
        this.dialogTablePage.pageSize = val
        this.dialogTablePage.currentPage = 1
        this.getShortMessageFun()
      },
      // 切换页码
      dialogCurrentChange(val) {
        this.shortHistoryParams.currentPage = val
        this.dialogTablePage.currentPage = val
        this.getShortMessageFun()
      }
    },
    // 当前组件路由守卫
    beforeRouteEnter(to, from, next) {
      next()
    },
    beforeRouteLeave(to, from, next) {
      this.$destroy()
      next();
    },
    watch:{
      'selectVal.businessType':{
        handler(val){
          if (val != '' && val != undefined && val != null) {
            this.content = ''
            this.msgTemplate = []
            this.getMessageTemplate(val)
          }
        },
        immediate: true
      }
    },
  }
</script>

<style scoped>

  .el-breadcrumb {
    padding: 10px 0 !important;
  }

  .el-button--primary {
    margin-top: 5px !important;
  }

</style>
